package cn.dansj.common.utils.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

class NumberSerializer extends JsonSerializer<Number> {
    public final static NumberSerializer INSTANCE = new NumberSerializer();

    @Override
    public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else if (serializers.isEnabled(NumericFeature.USE_STRING_FOR_NUMERIC)) {
            gen.writeString(value.toString());
        } else {
            if (value instanceof Long || value instanceof AtomicLong) {
                gen.writeNumber(value.longValue());
            } else if (value instanceof Integer || value instanceof AtomicInteger) {
                gen.writeNumber(value.intValue());
            } else if (value instanceof Double) {
                gen.writeNumber(value.doubleValue());
            } else if (value instanceof Float) {
                gen.writeNumber(value.floatValue());
            } else if (value instanceof Short) {
                gen.writeNumber(value.shortValue());
            } else if (value instanceof Byte) {
                gen.writeNumber(value.byteValue());
            } else {
                // 默认情况，直接写入（可能会转成最合适的类型）
                gen.writeNumber(value.toString());
            }
        }
    }
}